package com.feiluan.service;

import com.feiluan.util.RedisUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


@Component
public class TokenService {

    @Autowired
    private BasicService basicService;

    @Autowired
    private RedisUtil redisUtil;

    private final String uri = "http://39.99.205.81:81/iot/auth/getAccessToken?appId=105c7a93c459a501491c1e9824bb1c09&appSecret=0e2f3ad804be2bbdef8820a20146c066";

    public String getAccessToken() {
        String accessToken = (String) redisUtil.get("accessToken");
        if (accessToken != null && !StringUtils.isEmpty(accessToken)) {
            return accessToken;
        } else {
            ResponseEntity<String> result = basicService.postProxy(uri, null, null, String.class);
            JsonObject jsonObject = new Gson().fromJson(result.getBody(), JsonObject.class);
            accessToken = jsonObject.getAsJsonObject("body").get("accessToken").getAsString();
            Integer expiresIn = jsonObject.getAsJsonObject("body").get("expiresIn").getAsInt();
            redisUtil.set("accessToken", accessToken, expiresIn);
            return accessToken;
        }
    }

}



